package tenantchannellogic

import (
	"context"
	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/tenant/channel"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/tenant/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ThirdpartyBankListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewThirdpartyBankListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ThirdpartyBankListLogic {
	return &ThirdpartyBankListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ThirdpartyBankListLogic) ThirdpartyBankList(in *rpc.ThirdpartyBankListRequest) (*rpc.ThirdpartyBankListResponse, error) {
	var (
		CommonResp rpc.CommonResp
		bankList   []schema.TenantChannelThirdpartyBank
		err        error
	)

	thirdPartyModel := model.NewTenantChannelThirdpartyBankModel(l.ctx, l.svcCtx.Db)
	if in.AgentName != "" || in.BankName != "" || in.BankCode != "" {
		bankList, err = thirdPartyModel.GetThirdpartyBankByFilter(in.AgentName, in.BankName, in.BankCode)
	} else {
		bankList, err = thirdPartyModel.GetAllThirdpartyBanks()
	}

	if err != nil {
		CommonResp.Code = xerrors.DBError
		CommonResp.Message = "Database operation error"
		return &rpc.ThirdpartyBankListResponse{
			CommonResp: &CommonResp,
		}, err
	}

	var records []*rpc.ThirdpartyBank

	for _, agentBank := range bankList {
		records = append(records, &rpc.ThirdpartyBank{
			Id:        agentBank.ID,
			AgentName: agentBank.AgentName,
			BankName:  agentBank.BankName,
			BankCode:  agentBank.BankCode,
			Sort:      agentBank.Sort,
			Status:    agentBank.Status,
		})
	}

	CommonResp.Message = "Success"
	return &rpc.ThirdpartyBankListResponse{
		Records:    records,
		CommonResp: &CommonResp,
	}, nil
}
